import HTTP from '@/utils/request'
import {
    createOrder
} from '@/services/order/order'

export const getOpenId = (params) => {
    return HTTP.request('POST', {
        url: '/pay/wechat/getOpenid',
        params
    })
}

export const addOrder = (params) => {
    return HTTP.request('POST', {
        url: `/pay/wechat/createOrder?openid=${params.openid}&orderId=${params.orderId}`,
        // params
    })
}

const queryStatus = (orderId) => {
    return HTTP.request('GET', {
        url: `/pay/wechat/queryStatus/${orderId}`,
        // params
    })
}

const queryPayStatus = (id) => {
    const fun = async (resolve, reject) => {
        const res = await queryStatus(id)
        if (res.code === 200) {
            if (res.data.payStatus === '01') {
                resolve(res.data)
            } else {
                setTimeout(() => {
                    fun(resolve, reject)
                }, 300)
            }
        } else {
            reject(res.msg)
        }
    }
    return new Promise((resolve, reject) => {
        console.log('05')
        fun(resolve, reject)
    })
}

export const wxPayApi = ({
    params,
    orderId
}, fun, errFun) => {
    console.log('03')
    wx.requestPayment({
        timeStamp: params.timeStamp,
        nonceStr: params.nonceStr,
        package: params.package,
        signType: params.signType,
        paySign: params.paySign,
        success: () => {
            wx.showLoading({
                title: '正在生成课程',
            })
            queryPayStatus(orderId).then((data) => {
                wx.hideLoading()
                fun && fun(data)
            })
        },
        fail: (err) => {
            wx.showToast({
                title: '支付失败',
                icon: 'none'
            });
            errFun && errFun()
        }
    });
}

export function pay(params, fun, errFun) {
    createOrder(params.paymentData).then((res) => {
        if (res.code === 200) {
            const paymentParams = res.data;
            addOrder({
                openid: params.userInfo.openid,
                orderId: paymentParams.orderId
            }).then((cres) => {
                if (cres.code === 200) {
                    // 调用微信支付
                    wxPayApi({
                        params: cres.data,
                        orderId: paymentParams.orderId
                    }, fun, errFun)
                } else {
                    errFun && errFun()
                }
            })
        } else {
            wx.showToast({
                title: res.data.message || '获取支付参数失败',
                icon: 'none'
            });
            errFun && errFun()
        }
    }).catch((err) => {
        console.log(err)
        wx.showToast({
            title: '网络错误，请重试',
            icon: 'none'
        });
        errFun && errFun()
    })
}